import WX from 'weixin2html/WX';
import $ from 'jquery'
import Vue from 'vue'
import OneKit from './OneKit'
import {PROMISE} from 'oneutil'
import EventChannel from "./api/EventChannel"
import CanvasContext from './api/CanvasContext'
import Context from './api/Context'
import OffscreenCanvas from './api/OffscreenCanvas'
import CameraContext from './api/CameraContext'
// import CameraFrameListener from './api/CameraFrameListener'
import EditorContext from './api/EditorContext'
import './js/PrevewImage'

import MapContext from "./api/MapContext"
import SelectorQuery from "./api/SelectorQuery"
import WxIntersectionObserver from "./api/WxIntersectionObserver"
import Performance from "./api/Performance"
import XrFrameSystem from './api/XrFrameSystem'

class VueWX extends WX {
  constructor() {
    super()
  }
  createSelectorQuery() {
    return new SelectorQuery(this);
  }

  setNavigationBarTitle(wx_object) {
    const wx_title = wx_object.title
    const current = OneKit.current()
    current.$emit("setNavigationBarTitle", { title: wx_title })
    $("#onekit_navigationBar_title").html(wx_title);
    //console.log('111');
    // if (wx_object.success) wx_object.wx_success();
    if (wx_object.success) wx_object.success();
    if (wx_object.complete) wx_object.complete();

  }

  showNavigationBarLoading() {
    $("#onekit_navigationBar_title_loading").show();
  }

  hideNavigationBarLoading() {
    $("#onekit_navigationBar_title_loading").hide();
  }

  hideHomeButton() {
    console.warn('is not currently supported')
  }

  setNavigationBarColor(wx_object) {

    const wx_frontColor = wx_object.frontColor
    const wx_backgroundColor = wx_object.backgroundColor
    // const wx_animation = wx_object.animation


    $("#onekit_navigationBar").css("color", wx_frontColor)
    $("#onekit_navigationBar").css("background", wx_backgroundColor)

  }

  setBackgroundTextStyle(wx_object) {
    let wx_textStyle = wx_object.textStyle
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    if (wx_textStyle == 'dark') {
      OneKit.current().$parent.$parent.refreshColor = '#000000'
    } else {
      OneKit.current().$parent.$parent.refreshColor = '#ffffff'
    }
    PROMISE((SUCCESS) => {
      const res = {
        errMsg: "setBackgroundTextStyle:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  setBackgroundColor(wx_object) {
    let wx_backgroundColor = wx_object.backgroundColor
    let wx_backgroundColorTop = wx_object.backgroundColorTop
    // eslint-disable-next-line no-unused-vars
    let wx_backgroundColorBottom = wx_object.backgroundColorBottom
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null
    if (wx_backgroundColorTop) {
      $('.pull-to-refresh-layer').css('background', wx_backgroundColorTop)
    } else {
      $('.pull-to-refresh-layer').css('background', wx_backgroundColor)
    }
    PROMISE((SUCCESS) => {
      const res = {
        errMsg: "setBackgroundTextStyle:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  setTabBarBadge(wx_object) {
    let wx_index = wx_object.index
    let wx_text = wx_object.text
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    if (wx_text.length > 4) {
      wx_text = ' ... '
    }

    const tabBar = document.querySelectorAll('.tab-bar > .item')
    if (wx_index >= tabBar.length) {
      return
    }
    tabBar[wx_index].style.position = 'relative'

    let badge
    if (tabBar[wx_index].childNodes[2]) {
      badge = tabBar[wx_index].childNodes[2]
    } else {
      badge = document.createElement('div')
    }

    badge.style.backgroundColor = 'red'
    badge.style.color = 'white'
    badge.style.height = '15px'
    badge.style.width = 'auto'
    badge.style.maxWidth = '30px'
    badge.style.position = 'absolute'
    badge.style.left = '52%'
    badge.style.top = 0
    badge.style.borderRadius = '7px'
    badge.style.paddingLeft = '3px'
    badge.style.paddingRight = '3px'
    badge.innerText = wx_text

    if (!tabBar[wx_index].childNodes[2]) {
      tabBar[wx_index].appendChild(badge)
    }

    PROMISE((SUCCESS) => {
      const res = {
        errMsg: "setTabBarBadge:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)

  }

  removeTabBarBadge(wx_object) {
    let wx_index = wx_object.index
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    const tabBar = document.querySelectorAll('.tab-bar > .item')

    if ((wx_index < tabBar.length && wx_index >= 0) && tabBar[wx_index].children.length == 3) {
      tabBar[wx_index].removeChild(tabBar[wx_index].lastElementChild)

      PROMISE((SUCCESS) => {
        const res = {
          errMsg: "removeTabBarBadge:ok"
        }
        SUCCESS(res)
      }, wx_success, wx_fail, wx_complete)
    }
  }

  showTabBarRedDot(wx_object) {
    let wx_index = wx_object.index
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    const tabBar = document.querySelectorAll('.tab-bar > .item')
    if (wx_index >= tabBar.length) {
      return
    }

    const redDot = document.createElement('div')
    redDot.style.width = '10px'
    redDot.style.height = '10px'
    redDot.style.borderRadius = '50%'
    redDot.style.backgroundColor = 'red'
    redDot.style.position = 'absolute'
    redDot.style.top = '0'
    redDot.style.left = '52%'

    if (wx_index < tabBar.length && wx_index >= 0) {
      tabBar[wx_index].style.position = 'relative'
      tabBar[wx_index].appendChild(redDot)

      PROMISE((SUCCESS) => {
        const res = {
          errMsg: "showTabBarRedDot:ok"
        }
        SUCCESS(res)
      }, wx_success, wx_fail, wx_complete)
    }
  }

  hideTabBarRedDot(wx_object) {
    let wx_index = wx_object.index
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    const tabBar = document.querySelectorAll('.tab-bar > .item')
    if ((wx_index < tabBar.length && wx_index >= 0) && tabBar[wx_index].children.length == 3) {
      tabBar[wx_index].removeChild(tabBar[wx_index].lastElementChild)

      PROMISE((SUCCESS) => {
        const res = {
          errMsg: "hideTabBarRedDot:ok"
        }
        SUCCESS(res)
      }, wx_success, wx_fail, wx_complete)
    }
  }

  setTabBarStyle(wx_object) {
    let wx_color = wx_object.color
    let wx_selectedColor = wx_object.selectedColor
    let wx_backgroundColor = wx_object.backgroundColor
    let wx_borderStyle = wx_object.borderStyle
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    const vm = OneKit.current()

    PROMISE((SUCCESS, FAIL) => {
      let res
      if (vm.$parent.$parent.selectedColor) {
        vm.$parent.$parent.color = wx_color
        vm.$parent.$parent.selectedColor = wx_selectedColor
        vm.$parent.$parent.backgroundColor = wx_backgroundColor

        const tabBar = document.querySelector('.tab-bar')
        if (wx_borderStyle == "white") {
          tabBar.style.borderTop = '1px solid #f5f5f5'
        } else if (wx_borderStyle == "black") {
          tabBar.style.borderTop = '1px solid #cbcbcb'
        }
        res = {
          errMsg: "setTabBarStyle:ok"
        }
        SUCCESS(res)
      } else {
        res = {
          errMsg: "setTabBarStyle:fail not TabBar page"
        }
        FAIL(res)
      }
      console.log(res);
    }, wx_success, wx_fail, wx_complete)
  }

  setTabBarItem(wx_object) {
    let wx_index = wx_object.index
    let wx_text = wx_object.text
    let wx_iconPath = wx_object.iconPath
    let wx_selectedIconPath = wx_object.selectedIconPath
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    let res
    PROMISE((SUCCESS, FAIL) => {
      if (OneKit.current().$parent.$parent.tabs) {
        const tab = OneKit.current().$parent.$parent.tabs[wx_index]
        tab.name = wx_text
        tab.normal = wx_iconPath
        tab.selected = wx_selectedIconPath
        res = {
          errMsg: "setTabBarItem:ok"
        }
        SUCCESS(res)
      } else {
        res = {
          errMsg: "setTabBarItem:fail not TabBar page"
        }
        FAIL(res)
      }
      console.log(res);
    }, wx_success, wx_fail, wx_complete)
  }

  showTabBar(wx_object) {
    // eslint-disable-next-line no-unused-vars
    // let wx_animation = wx_object.animation || false
    // let wx_success = wx_object.success;
    // let wx_fail = wx_object.fail;
    // let wx_complete = wx_object.complete;
    // wx_object = null

    // const tabBar = $('.tab-bar')[0]
    // tabBar.style.display = ''

    // PROMISE((SUCCESS) => {
    //   const res = {
    //     errMsg: "showTabBar:ok"
    //   }
    //   SUCCESS(res)
    // }, wx_success, wx_fail, wx_complete)
    console.warn('is not currently supprted')
  }

  hideTabBar(wx_object) {
    // eslint-disable-next-line no-unused-vars
    // let wx_animation = wx_object.animation || false
    // let wx_success = wx_object.success;
    // let wx_fail = wx_object.fail;
    // let wx_complete = wx_object.complete;
    // wx_object = null

    // const tabBar = $('.tab-bar')[0]
    // tabBar.style.display = 'none'

    // PROMISE((SUCCESS) => {
    //   const res = {
    //     errMsg: "hideTabBar:ok"
    //   }
    //   SUCCESS(res)
    // }, wx_success, wx_fail, wx_complete)
    console.warn('is not currently supprted')
  }

  loadFontFace() {
    console.warn('is not currently supprted')
  }

  startPullDownRefresh(wx_object) {
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    PROMISE((SUCCESS) => {
      OneKit.current().$emit('startPullDownRefresh');
      const res = {
        errMsg: "startPullDownRefresh:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  stopPullDownRefresh(wx_object) {
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null

    PROMISE((SUCCESS) => {
      OneKit.current().$emit('stopPullDownRefresh');
      const res = {
        errMsg: "stopPullDownRefresh:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  // onPullDownRefresh(wx_object) {
  //   this.onPullDownRefresh = wx_object;
  // }

  pageScrollTo(wx_object) {
    const wx_scrollTop = wx_object.scrollTop;
    //const wx_duration = wx_object.duration || 300
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null
    PROMISE((SUCCESS) => {
      $(".onekit-page")[0].scrollTo(0, wx_scrollTop);
      if (SUCCESS) {
        SUCCESS()
      }
    }, wx_success, wx_fail, wx_complete)
  }


  switchTab(wx_object) {
    let wx_url = wx_object.url;
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null
    ///////////
    let wx_res;
    try {
      const vue_url = wx_url
      const current = OneKit.current();
      current.$emit("switchtab", { url: vue_url })
      OneKit.current().$router.push({
        path: `/${OneKit.fixurl(vue_url)}`
      })
      wx_res = {
        switchTab: 'ok'
      };
      if (wx_success) {
        wx_success(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    } catch (e) {
      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }
  }

  reLaunch(wx_object) {
    let wx_url = wx_object.url;
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null
    ///////////
    let wx_res;
    try {
      const vue_path = wx_url
      const pageCount = OneKit.current().$route.length - 1
      OneKit.current().$router.go(-pageCount);
      OneKit.current().$router.replace(vue_path);
      wx_res = {
        reLaunch: 'ok'
      };
      if (wx_success) {
        wx_success(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    } catch (e) {

      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }
  }

  redirectTo(wx_object) {
    let wx_url = wx_object.url;
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    wx_object = null
    ///////////
    let wx_res;
    try {
      const parameter = wx_url.includes("?") ? wx_url.substring(wx_url.indexOf("?"), wx_url.length) : ''
      const vue_path = `/${OneKit.fixurl(wx_url) + parameter}`
      window.onekit_rout_begin = new Date().getTime()
      OneKit.current().$router.replace(vue_path);
      wx_res = {
        redirectTo: 'ok'
      };
      if (wx_success) {
        wx_success(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    } catch (e) {

      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }
  }

  navigateTo(wx_object) {
    const wx_url = wx_object.url;
    const wx_events = wx_object.events;
    //const wx_success = wx_object.success;
    //const wx_fail = wx_object.fail;
    //const wx_complete = wx_object.complete;
    wx_object = null
    ///////////
    //PROMISE((SUCCESS) => {
    const parameter = wx_url.includes("?") ? wx_url.substring(wx_url.indexOf("?"), wx_url.length) : ''
    const vue_path = `/${OneKit.fixurl(wx_url) + parameter}`
    const channel = new Vue();
    for (const event_key in wx_events) {
      const event_func = wx_events[event_key]
      channel.$on(event_key, event_func);
    }
    const eventChannel = new EventChannel(channel);
    const eventChannelID = new Date().getTime()
    window.eventChannels[eventChannelID] = eventChannel
    //////
    window.onekit_rout_begin = new Date().getTime()
    OneKit.current().$router.push({
      path: vue_path,
      query: { eventChannelID }
    })
    //  if (SUCCESS) {
    //    SUCCESS()
    //  }
    //  }, wx_success, wx_fail, wx_complete)
  }

  navigateBack(wx_object) {
    const wx_delta = wx_object ? (wx_object.delta || 1) : 1; // 返回的页面数
    const wx_success = wx_object && wx_object.success;
    const wx_fail = wx_object && wx_object.fail;
    const wx_complete = wx_object && wx_object.complete;
    wx_object = null
    ///////////
    let wx_res;
    try {
      const vue_delta = wx_delta
      OneKit.current().$router.go(-vue_delta);
      wx_res = {
        navigateBack: 'ok'
      };
      if (wx_success) {
        wx_success(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    } catch (e) {

      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }
  }

  showToast(wx_object) {
    let tipTxt = wx_object.title;
    let time;
    if (!wx_object.duration) {
      time = 1500;
    } else {
      time = wx_object.duration
    }
    let mask;
    if (!wx_object.mask) {
      mask = false
    } else {
      mask = wx_object.mask
    }
    let icon;
    if (!wx_object.icon) {
      icon = "success"
    } else {
      icon = wx_object.icon;
    }
    let image;
    if (wx_object.image) {
      image = wx_object.image;
    }
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    let wx_res;
    try {
      let viewportID = document.getElementById("viewport");
      if (!viewportID) {
        let oMeta = document.createElement('meta');
        oMeta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;';
        oMeta.name = 'viewport';
        oMeta.id = 'viewport';
        document.getElementsByTagName('head')[0].appendChild(oMeta)
      }
      $(".xsw_toast").remove();
      let popToastHtml = "";
      popToastHtml += `<div class="xsw_showToast"> `;
      if (mask == true) {
        popToastHtml += `<div class="xsw_bei" style="position: fixed;width: 100%;height: 100%;top: 0;left: 0;background-color: #FFFFFF;opacity: 0.01;z-index: 999999999999999999999"></div>`
      }
      popToastHtml += `<div class="pop-toast" style="position: fixed;  width: 140px;  height: 140px;  text-align: center;background-color: #555;border-radius: 10px;box-shadow: 0 2px 8px #555 ;right: 50%;top: 50%;margin: -70px -70px 0 0;z-index: 9999999999999999999999">`;
      if (image) {
        popToastHtml += `<img src="${image}" style="width: 50px;margin-top: 12px;">`
        popToastHtml += ` <div class="toast-tip" style=" font-size: 16px;  color: #fff;  height: 45px;overflow: hidden;width:130px; word-wrap: break-word; text-align: center;padding: 0 5px ;margin-bottom: 10px;">${tipTxt}</div>
                                  </div></div>`;
      } else {
        if (icon == "none") {
          popToastHtml += ` <img  style="width: 50px;margin-top: 12px;display: none">`
          popToastHtml += ` <div class="toast-tip" style=" font-size: 16px;  color: #fff;  height: 45px;overflow: hidden;width:130px; word-wrap: break-word; text-align: center;padding: 0 5px ;margin-top: 45px; ">${tipTxt}</div>
                                  </div></div>`;
        } else {
          if (icon == "success") {
            popToastHtml += `<canvas id="x_canvas" style="padding-top: 10px" width="140px" height="50px"></canvas>`;
          } else if (icon == "loading") {
            popToastHtml += `<div id="xsw_canvas" style="140px;height: 60px;"><img src="/onekit/loading.gif" style="width:32px;height:32px;margin-top:28px;"/></div>`;
          }
          popToastHtml += ` <div class="toast-tip" style=" font-size: 16px;  color: #fff;  height: 45px;overflow: hidden;width:130px; word-wrap: break-word; text-align: center;padding: 0 5px ;margin-bottom: 10px;margin-top: 10px;">${tipTxt}</div>
                                  </div></div>`;
        }
      }
      $("body").append(popToastHtml);
      $("body").css({ "position": "relative" });
      if (icon == "success") {
        /////////////////////////////////////////////////画勾
        let cvs = document.getElementById('x_canvas'); //画布
        let ctx = cvs.getContext('2d'); // 画笔
        ctx.lineWidth = 4; //线宽
        ctx.strokeStyle = "#fff"; //线的颜色
        ctx.moveTo(55, 35);
        ctx.lineTo(65, 45);
        ctx.lineTo(90, 15);
        ctx.stroke();
      }
      // else if (icon == "loading") {
      //   console.log('xxxxxxxxxxxxxxxxx', this.interaction)
      //   /////////////////////////////////////////////////
      //   this.interaction.loading();
      // }
      /////////////////////////////////////////////////
      if (time != "" || time != 0) {
        setTimeout(function () {
          $("#viewport").remove();
          $(".xsw_showToast").remove();
        }, time);
      }
      wx_res = { showToast: "ok" };
      if (wx_success) {
        wx_success(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }

    } catch (e) {
      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }
  }

  showModal(wx_object) {
    let title = wx_object.title || ""
    let content = wx_object.content || ""
    let showCancel = wx_object.showCancel
    let cancelColor = wx_object.cancelColor
    let confirmColor = wx_object.confirmColor

    let cancelText;
    if (!wx_object.cancelText) {
      cancelText = "取消";
    } else {
      cancelText = wx_object.cancelText;
    }
    let confirmText;
    if (!wx_object.confirmText) {
      confirmText = "确定";
    } else {
      confirmText = wx_object.confirmText;
    }
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    let wx_res;
    try {
      let viewportID = document.getElementById("viewport");
      if (!viewportID) {
        let oMeta = document.createElement('meta');
        oMeta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0';
        oMeta.name = 'viewport';
        oMeta.id = 'viewport';
        document.getElementsByTagName('head')[0].appendChild(oMeta);
      }
      $(".xsw_showModa").remove();
      let showModalHtml = "";
      showModalHtml += `<div class="xsw_showModa" >`
      showModalHtml += `<div class="xsw_showModaBei" style="position: fixed;width: 100%;height: 100%;top: 0;left: 0; background-color: #333;opacity: 0.4;z-index: 999999999999999999999"></div>`
      showModalHtml += `<div class="xsw_modal-data" style="width:220px;  border-radius: 10px;  top: 50%;  left: 50%;  box-shadow: 0 2px 8px #555 ;  background-color: #fff;padding:15px 15px;  text-align:center;  z-index: 9999999999999999999999;  position: fixed;margin:">
                                        <div style="text-align: center;font-size: 18px;font-weight: bold">${title}</div><br>
                                        <div style="text-align: center;font-size: 16px;margin-bottom: 30px;color:#7f7f7f;">${content} </div><br>`;
      if (showCancel == false) {
        showModalHtml += `<div style="position: absolute;bottom: 5px;width:100%;border-top:1px solid #f6f6f6;left:0;"><div class="yesDian" style="width: 110px;display: inline-block;cursor: pointer;border-radius: 10px;padding: 8px 0;font-size: 18px;font-weight: bold;color:#576b95;">${confirmText}</div></div>`
      } else {
        showModalHtml += ` <div style="position: absolute;bottom: 0px;border-top:1px solid #f6f6f6;"><div class="noDian" style="width: 109.5px;display: inline-block;margin-bottom: 0;cursor: pointer;border-radius: 0 0 0 10px;padding: 8px 0;color: #000000;font-size: 18px;border-right:1px solid #f6f6f6;font-weight: bold;">${cancelText}</div><div class="yesDian" style="width: 109.5px;display: inline-block;cursor: pointer;border-radius: 0 0 10px 0;padding: 8px 0;font-size: 18px;font-weight: bold;color:#576b95;">${confirmText}</div></div>`
      }
      `></div></div>`;
      $("body").append(showModalHtml);
      if (cancelColor) {
        $('.noDian').css({ 'color': cancelColor })
      }
      if (confirmColor) {
        $('.yesDian').css({ 'color': confirmColor })
      }
      let outerWidth = -$('.xsw_modal-data').outerHeight() / 2;
      let modal = document.querySelector('.xsw_modal-data');
      modal.style.margin = outerWidth + 'px 0 0 -125px';
      //     $('.xsw_modal-data').css({'margin-left:','"+outerWidth+"'})
      $("body").css({ "position": "relative" });
      $('.noDian').click(function () {
        $("#viewport").remove();
        $(".xsw_showModa").remove();
        wx_res = {
          cancel: true,
          confirm: false,
          showModal: "ok"
        };
        if (wx_success) {
          wx_success(wx_res);
        }
        if (wx_complete) {
          wx_complete(wx_res);
        }
      });
      $('.yesDian').click(function () {
        $("#viewport").remove();
        $(".xsw_showModa").remove();
        wx_res = {
          cancel: false,
          confirm: true,
          content: null,
          showModal: "ok"
        };
        if (wx_success) {
          wx_success(wx_res);
        }
        if (wx_complete) {
          wx_complete(wx_res);
        }
      });
    } catch (e) {
      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }

  }

  showLoading(wx_object) {
    let tipTxt = wx_object.title;
    let mask;
    if (!wx_object.mask) {
      mask = false
    } else {
      mask = wx_object.mask
    }
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    let wx_res;
    try {
      let viewportID = document.getElementById("viewport");
      if (!viewportID) {
        let oMeta = document.createElement('meta');
        oMeta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;';
        oMeta.name = 'viewport';
        oMeta.id = 'viewport';
        document.getElementsByTagName('head')[0].appendChild(oMeta);
      }
      $(".xsw_toast").remove();
      let popToastHtml = "";
      popToastHtml += `<div class="xsw_showLoading"> `;
      if (mask == true) {
        popToastHtml += `<div class="xsw_bei" style="position: fixed;width: 100%;height: 100%;top: 0;left: 0;background-color: #262626;opacity: 0.4;z-index: 999999999999999999999"></div>`
      }
      popToastHtml += `<div class="pop-toast" style="position: fixed;  width: 140px;  height: 140px;  text-align: center;background-color: #555;border-radius: 10px;box-shadow: 0 2px 8px #555 ;right: 50%;top: 50%;margin: -70px -70px 0 0;z-index: 9999999999999999999999">`;
      popToastHtml += `<div id="xsw_canvas" style="height: 60px;color: red;border:4px dashed #fff;width: 60px;text-align: center;margin: 10px auto;border-radius: 100%;"></div>`;
      popToastHtml += ` <div class="toast-tip" style=" font-size: 16px;  color: #fff;  height: 45px;overflow: hidden;width:130px; word-wrap: break-word; text-align: center;padding: 0 5px ;margin-bottom: 10px;margin-top: 10px;">${tipTxt}</div>
                                  </div></div>`;
      $("body").append(popToastHtml);
      $("body").css({ "position": "relative" });
      this.interaction.loading();
      wx_res = { showLoading: "ok" };
      if (wx_success) {
        wx_success(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }

    } catch (e) {
      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_fail);
      }
      if (wx_complete) {
        wx_complete(wx_complete);
      }
    }
  }

  showActionSheet(wx_object) {
    let itemList = wx_object.itemList;
    let itemColor = wx_object.itemColor;
    let wx_success = wx_object.success;
    let wx_fail = wx_object.fail;
    let wx_complete = wx_object.complete;
    let index;
    let wx_res;
    try {
      let viewportID = document.getElementById("viewport");
      if (!viewportID) {
        let oMeta = document.createElement('meta');
        oMeta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;';
        oMeta.name = 'viewport';
        oMeta.id = 'viewport';
        document.getElementsByTagName('head')[0].appendChild(oMeta);
      }
      $(".xsw_showActionSheet").remove();
      let showActionSheetHtml = "";
      showActionSheetHtml += `<div class="xsw_showActionSheet" >
                                        <div class="xsw_showActionSheetBei" style="position: fixed;width: 100%;height: 100%;top: 0;left: 0; background-color: #333;opacity: 0.4;z-index: 999999999999999999999"></div>
                                        <div class="xsw_showActionSheet-data" style="width:220px;  border-radius: 5px;  top: 50%;  left: 50%;  box-shadow: 0 2px 8px #555 ;  background-color: #fff;  border:1px solid #000; text-align:center;  z-index: 9999999999999999999999;  position: fixed;color: #000000">
                                            <div style="text-align: left">`;
      let xsw_length;
      if (itemList.length > 6) {
        xsw_length = 6;
      } else {
        xsw_length = itemList.length;
      }
      for (let xsw_i = 0; xsw_i < xsw_length; xsw_i++) {
        showActionSheetHtml += `<div class="xsw_list" style="border-bottom: 1px solid #cccccc;padding: 10px 0 10px 10px;">${itemList[xsw_i]}</div>`
      }
      showActionSheetHtml += `</div></div></div>`;
      $("body").append(showActionSheetHtml);
      let outerWidth = -$('.xsw_showActionSheet-data').outerHeight() / 2;
      let modal = document.querySelector('.xsw_showActionSheet-data');
      modal.style.margin = outerWidth + 'px 0 0 -110px';
      $('.xsw_list:last').css({ 'border': "none" })
      if (itemColor) {
        $('.xsw_showActionSheet-data').css({ 'color': itemColor })
      }
      $('.xsw_list').click(function () {
        let thisHtml = $(this).html();
        for (let x in itemList) {
          if (thisHtml == itemList[x]) {
            index = x;
          }
        }
        wx_res = {
          showActionSheet: "ok",
          tapIndex: index
        };
        if (wx_success) {
          wx_success(wx_res);
        }
        if (wx_complete) {
          wx_complete(wx_res);
        }
      });
      $(".xsw_showActionSheet").click(function () {
        $("#viewport").remove();
        $(".xsw_showActionSheet").remove();
      });
    } catch (e) {
      wx_res = { errMsg: e.message };
      if (wx_fail) {
        wx_fail(wx_res);
      }
      if (wx_complete) {
        wx_complete(wx_res);
      }
    }
  }

  hideToast() {
    $("#viewport").remove();
    $(".xsw_showToast").remove();
  }

  hideLoading() {
    $("#viewport").remove();
    $(".xsw_showLoading").remove();
  }

  enableAlertBeforeUnload(wx_object) {
    let wx_message = wx_object.message
    let wx_success = wx_object.success
    let wx_fail = wx_object.fail
    let wx_complete = wx_object.complete
    wx_object = null

    window.enableAlertBeforeUnload = wx_message


    PROMISE((SUCCESS) => {
      const res = {
        errMsg: "enableAlertBeforeUnload:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  disableAlertBeforeUnload(wx_object) {
    let wx_success = wx_object.success
    let wx_fail = wx_object.fail
    let wx_complete = wx_object.complete
    wx_object = null
    window.enableAlertBeforeUnload = ''

    PROMISE((SUCCESS) => {
      const res = {
        errMsg: "disableAlertBeforeUnload:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  //////////// 地图 ////////////
  createMapContext(mapId) {
    return new MapContext(mapId)
  }
  //////////// 画布 ////////////
  createContext() {
    return new Context()
  }
  createCanvasContext(id) {
    const eCanvas = document.getElementById(id)

    const computedStyle = window.getComputedStyle(eCanvas)
    const width = computedStyle.width
    const height = computedStyle.height
    eCanvas.width = width.substr(0, width.length - 2)
    eCanvas.height = height.substr(0, height.length - 2)
    const canvasContext = eCanvas.getContext("2d")
    return new CanvasContext(canvasContext, eCanvas)
  }

  createOffscreenCanvas() {
    return new OffscreenCanvas()
  }

  canvasToTempFilePath() {
    console.warn('is not currently supprted')
  }

  canvasPutImageData() {
    console.warn('is not currently supprted')
  }

  canvasGetImageData() {
    console.warn('is not currently supprted')
  }


  ////////////////// 相机 //////////////////////////
  createCameraContext() {
    const camaraContext = document.getElementsByTagName('video')
    return new CameraContext(camaraContext)
  }

  //////////////////// 图片  ///////////////////////
  previewMedia(wx_object) {
    const wx_sources = wx_object.sources
    const wx_current = wx_object.current || 0
    const wx_showmenu = wx_object.showmenu || true
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    wx_object = null

    OneKit.current().$router.push({ path: '/onekit/previewMedia', query: { sources: wx_sources, current: wx_current, showmenu: wx_showmenu } })

    return PROMISE((SUCCESS) => {
      const res = { errMsg: "previewMedia:ok" }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  //////////////////// 视频  ///////////////////////
  openVideoEditor() {
    console.warn('is not currently supported')
  }

  //////////////////  Editor ////////////////////////
  createEditorContext(id) {
    const editor = document.getElementById(id)
    return new EditorContext(editor)
  }

  drawCanvas(object) {
    let canvasId = object.canvasId;
    let actions = object.actions;
    // let reserve = object.reserve;
    object = null
    ///////////////////
    const eCanvas = document.getElementById(canvasId)
    const computedStyle = window.getComputedStyle(eCanvas)
    const width = computedStyle.width
    const height = computedStyle.height
    eCanvas.width = width.substr(0, width.length - 2)
    eCanvas.height = height.substr(0, height.length - 2)
    let context = eCanvas.getContext("2d");
    // context.clearRect(0, 0, eCanvas.width, eCanvas.height);
    for (let a = 0; a < actions.length; a++) {
      let action = actions[a];
      let data = action.data;
      let method = action.method;
      //
      switch (method) {
        case "setStrokeStyle":
          context.strokeStyle = data[1];
          break
        case "drawImage": {
          const image = new Image()
          image.onload = function () {
            context.drawImage(this, data[1], data[2])
          }
          image.src = data[0]
          break
        }
        case "setFillStyle": {
          let fillStyle = data[0];
          if (fillStyle == "normal") {
            let setFillStyle = data[1]
            context.fillStyle = setFillStyle;
          } else if (fillStyle == "radial") {
            let colorStops = data[2];
            let colors = [colorStops.length];
            let stops = [colorStops.length];
            for (let s = 0; s < colorStops.length; s++) {
              stops[s] = (colorStops[s])[0];
              let rgba = (colorStops[s])[1];
              colors[s] = rgba;
            }
            let info = data[1];
            let cgx = info[0];
            let cgy = info[1];
            let cgr = info[2];
            let gradient = context.createRadialGradient(cgx, cgy, cgr, colors, stops);
            context.fillStyle = gradient;

          } else if (fillStyle == "linear") {
            let colorStops = data[2];
            let colors = [colorStops.length];
            let stops = [colorStops.length];
            for (let s = 0; s < colorStops.length; s++) {
              stops[s] = (colorStops[s])[0];
              let rgba = (colorStops[s])[1];
              colors[s] = rgba;
            }
            let info = data[1];
            let lgx0 = info[0];
            let lgy0 = info[1];
            let lgx1 = info[2];
            let lgy1 = info[3];
            let gradient = context.createLinearGradient(lgx0, lgy0, lgx1, lgy1, colors, stops);
            context.fillStyle = gradient;
          } else {
            console.error("[setFillStyle]", fillStyle + "");
          }
          break;
        }
        case "fillPath":
          context.beginPath();
          // context.globalAlpha = data[0];
          for (let d = 0; d < data.length; d++) {
            let item = data[d];
            let method2 = item.method;
            let data2 = item.data;
            switch (method2) {
              case "rect":
                context.fillRect(data2[0],
                  data2[1],
                  data2[2],
                  data2[3]);
                break;
              case "moveTo":
                context.moveTo(data2[0], data2[1]);
                break;
              case "lineTo":
                context.lineTo(data2[0], data2[1]);
                break;
              case "closePath":
                context.closePath();
                break;
              case "bezierCurveTo":
                context.bezierCurveTo(data2[0],
                  data2[1],
                  data2[2],
                  data2[3],
                  data2[4],
                  data2[5]);
                break;
              case "quadraticCurveTo":
                context.quadraticCurveTo(data2[0],
                  data2[1],
                  data2[2],
                  data2[3]);
                break;

              case "arc": {
                let x = data2[0];
                let y = data2[1];
                let r = data2[2];
                let a1 = data2[3];
                let a2 = data2[4];
                let counterclockwise = data2[5];
                context.arc(x, y, r, a1, a2, counterclockwise);
              }
                break;
              default:
                console.error("===========", method2);
                break;
            }
          }
          context.fill();
          break;
        case "strokePath":
          context.beginPath();
          // context.globalAlpha = data[0];
          for (let d = 0; d < data.length; d++) {
            let item = data[d];
            let method2 = item.method;
            let data2 = item.data;
            switch (method2) {
              case "rect":
                context.strokeRect(data2[0],
                  data2[1],
                  data2[2],
                  data2[3]);
                break;
              case "moveTo":
                context.moveTo(data2[0], data2[1]);
                break;
              case "lineTo":
                context.lineTo(data2[0], data2[1]);
                break;
              case "closePath":
                context.closePath();
                break;
              case "bezierCurveTo":
                context.bezierCurveTo(data2[0],
                  data2[1],
                  data2[2],
                  data2[3],
                  data2[4],
                  data2[5]);
                break;
              case "quadraticCurveTo":
                context.quadraticCurveTo(data2[0],
                  data2[1],
                  data2[2],
                  data2[3]);
                break;
              case "arc": {
                let x = data2[0];
                let y = data2[1];
                let r = data2[2];
                let a1 = data2[3];
                let a2 = data2[4];
                let counterclockwise = data2[5];
                context.arc(x, y, r, a1, a2, counterclockwise);
              }
                break;
              default:
                console.error("===========2", method2);
                break;
            }
          }
          context.stroke();
          break;
        case "setFontSize": {
          const font = `normal ${data[0]}px serif`
          console.log(font)
          context.font = font
          break
        }
        case "setLineWidth":
          context.lineWidth = data[0]
          break
        case "setGlobalAlpha":
          context.globalAlpha = data[0]
          break
        case "setShadow":
          context.shadowOffsetX = data[0]
          context.shadowOffsetY = data[1]
          context.shadowBlur = data[2]
          context.shadowColor = data[3]
          break
        case "setLineCap":
          context.lineCap = data[0]
          break
        case "setLineJoin":
          context.lineJoin = data[0]
          break
        case "setMiterLimit":
          if (data[1] != 0) {
            context.miterLimit = data[0] / data[1]
          }
          break
        default:
          console.log(method, data)
          context[method].apply(context, data)
          break;
      }
    }
  }
  ///////////////////////////////////////////

  login() {

    // const url = `https://m.v.qq.com/x/m/play?cid=mzc00200fh3z7x3&vid=x0036mfb4uf&rv=1614333979549`
    // const loginUrl = `https://open.weixin.qq.com/sns/explorer_broker?appid=wx68ff4e3ba9f84df4&redirect_uri=https://film.qq.com/weixin/login.html?ru=https%3A%2F%2Fm.v.qq.com%2Fx%2Fm%2Fplay%3Fcid%3Dmzc00200fh3z7x3%26vid%3Dx0036mfb4uf%26rv%3D1614333979549&success=1&type=wx&back=0&nochange=0&state=h5login&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect`

    // const weiXdeng = document.createElement('button')
    // weiXdeng.setAttribute('id', 'weiXingDeng')
    // weiXdeng.setAttribute('style', 'width:80%margin:20px 0 0 10%')
    // weiXdeng.setAttribute('onclick', 'OpenInterface.weixinDian()')
    // weiXdeng.innerText = '微信登录'
    // const firstDian = document.body.firstChild
    // document.body.insertBefore(weiXdeng, firstDian)
    // const zhiFdeng = document.createElement('button')
    // zhiFdeng.setAttribute('id', 'zhiFBDeng')
    // zhiFdeng.setAttribute('style', 'width:80%margin:20px 0 0 10%')
    // zhiFdeng.setAttribute('onclick', 'OpenInterface.zhiFBDian()')
    // zhiFdeng.innerText = '支付宝登录'
    // document.body.appendChild(zhiFdeng)
    // const weiBdeng = document.createElement('button')
    // weiBdeng.setAttribute('id', 'weiBoDeng')
    // weiBdeng.setAttribute('style', 'width:80%margin:20px 0 0 10%')
    // weiBdeng.setAttribute('onclick', 'OpenInterface.weiBoDian()')
    // weiBdeng.innerText = '微博登录'
    // document.body.appendChild(weiBdeng)
    // const QQdeng = document.createElement('button')
    // QQdeng.setAttribute('id', 'QQDeng')
    // QQdeng.setAttribute('style', 'width:80%margin:20px 0 0 10%')
    // QQdeng.setAttribute('onclick', 'OpenInterface.QQDian()')
    // QQdeng.innerText = 'QQ登录'
    // document.body.appendChild(QQdeng)
  }

  // weixinDian() {
  //   location.href =
  //     'https://open.weixin.qq.com/connect/qrconnect?appid=wx240ff52c65528fbb&scope=snsapi_login&redirect_uri=https%3A%2F%2Fwww.onekit.com%2Fpassport0%2Flogin%2FPlogin.php&state=' +
  //     Math.ceil(Math.random() * 1000) +
  //     '&login_type=jssdk&self_redirect=default'
  // }
  // zhiFBDian() {
  //   location.href =
  //     'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2018030502321064&scope=auth_user&redirect_uri=https://www.onekit.com/passport/login/ZFlogin.php&state=' +
  //     Math.ceil(Math.random() * 1000)
  // }
  // weiBoDian() {
  //   location.href =
  //     'https://api.weibo.com/oauth2/authorize?client_id=1741134067&redirect_uri=https%3A%2F%2Fwww.onekit.cn%2Fpassport0%2Flogin%2FWBlogin%2FWlogin.php&response_type=code'
  // }
  // QQDian() {
  //   location.href =
  //     'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101475870&redirect_uri=https://www.onekit.cn/passport0/login/QQlogin.php&state=' +
  //     Math.ceil(Math.random() * 1000)
  // }

  checkSession() {
    console.warn('is not currently supported')
  }

  reportMonitor() {
    console.warn('is not currently supported')
  }

  reportAnalytics() {
    console.warn('is not currently supported')
  }

  requestPayment(wx_object) {
    // 小程序参数
    const timestamp = wx_object.timestamp // 时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
    const nonceStr = wx_object.nonceStr // 随机字符串，长度为32个字符以下
    const package_s = wx_object.package // 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***（ package 为js关键词，所以取名为 package_s ）
    const signType = wx_object.signType // 签名算法
    const paySign = wx_object.paySign // 签名
    const wx_success = wx_object.success || ''
    const wx_fail = wx_object.fail || ''
    const wx_complete = wx_object.complete || ''
    //
    const res = {}
    this.chooseWXPay({
      // JS-SDK参数
      timestamp: timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
      nonceStr: nonceStr, // 支付签名随机串，不长于 32 位
      package: package_s, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
      signType: signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
      paySign: paySign, // 支付签名
      success: wx_success(res),
      fail: wx_fail(res),
      complete: wx_complete(res),
    })
  }


  openSetting() {
    OneKit.current().$router.push({ path: '/onekit/openSetting' })
  }

  getSetting(wx_object) {
    const wx_withSubscriptions = wx_object.withSubscriptions || false
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    let res = ''

    console.log(wx_withSubscriptions)

    const authSetting = JSON.parse(window.localStorage.getItem('authSetting'))

    if (wx_withSubscriptions) {
      const withSubscriptions = { mainSwitch: true }
      res = {
        authSetting,
        errMsg: "getSetting:ok",
        withSubscriptions
      }
    } else {
      res = {
        authSetting,
        errMsg: "getSetting:ok"
      }
    }

    return PROMISE((SUCCESS) => {
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  // Address

  addCard(wx_object) {
    const cardList = wx_object.cardList
    const wx_success = wx_object.success || ''
    const wx_fail = wx_object.fail || ''
    const wx_complete = wx_object.complete || ''
    // ///////////////////////////////
    this.openCard({
      cardList: cardList, // 需要添加的卡券列表
      success: wx_success,
      fail: wx_fail,
      complete: wx_complete,
    })
  }

  openCard(wx_object) {
    const cardList = wx_object.cardList
    const wx_success = wx_object.success || ''
    const wx_fail = wx_object.fail || ''
    const wx_complete = wx_object.complete || ''
    // ///////////////////////////////
    this.openCard({
      cardList: cardList, // 需要打开的卡券列表
      success: wx_success,
      fail: wx_fail,
      complete: wx_complete,
    })
  }

  checkIsSupportSoterAuthentication() {
    console.warn('is not currently supported')
  }

  startSoterAuthentication() {
    console.warn('is not currently supported')
  }

  checkIsSoterEnrolledInDevice() {
    console.warn('is not currently supported')
  }

  getWeRunData() {
    console.warn('is not currently supported')
  }

  createIntersectionObserver(component, options) {
    return new WxIntersectionObserver(component, options);
  }

  getPerformance() {
    return new Performance()
  }

  chooseLocation(wx_object) {
    const wx_latitude = wx_object.latitude
    const wx_longitude = wx_object.longitude
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    wx_object = null

    // const scope_userLocation = JSON.parse(window.localStorage.getItem('scope'))['scope.userLocation']

    const callbackID = new Date().getTime()
    PROMISE((SUCCESS, FAIL) => {
      // if (scope_userLocation) {
        window[callbackID] = (result) => {
          const res = result
          SUCCESS(res)
        }
      // } else {
      //   const err = { errMsg: "chooseLocation:fail auth deny" }
      //   FAIL(err)
      // }

    }, wx_success, wx_fail, wx_complete)

    window.open(`/onekit/pages/chooseLocation.html?callbackID=${callbackID}&latitude=${wx_latitude}&longitude=${wx_longitude}`, 'chooseLocation');

    //   const {latitude, longitude, success, fail, complete} = options
    //   PROMISE(SUCCESS => {
    //     this._mapinit()
    //     const map_container = document.createElement('div')
    //     map_container.setAttribute('style', 'height:100vh;width:100vw;')
    //     map_container.setAttribute('id', 'onekitmap-container')
    //     document.body.appendChild(map_container)
    //     const map = new AMap.Map('onekitmap-container', {
    //       resizeEnable: true,
    //       zoom: 16,
    //       center: [longitude, latitude]
    //     })
    //     const center_maker = new AMap.Marker({
    //       position: map.getCenter(),
    //       draggable: true,
    //       cursor: 'move',
    //       // 设置拖拽效果
    //       raiseOnDrag: true
    //     })

    //     center_maker.setMap(map)
    //     map.getCenter(res => {
    //       console.log(res)
    //     })
    //     center_maker.on('dragend', res => {
    //       const {lng, lat} = res.lnglat
    //       map.setCenter([lng, lat])
    //       // AMap.event.addListener(geolocation, 'complete', onComplete => {
    //         const geoCoder = new AMap.geoCoder({
    //           city: ''
    //         })

    //        geoCoder.getAddress([lng, lat], (status, result) => {
    //          console.log(status, result)
    //        })
    //         const resu = {
    //           errMsg: 'getLocation: ok',
    //           latitude: onComplete.position.lat,
    //           longitude: onComplete.position.lng,
    //           address: '',
    //           address
    //         }
    //         SUCCESS(resu)

    //       // })
    //     })
    //     const res = {

    //     }
    //     SUCCESS(res)
    //   }, success, fail, complete)
  }

  getLocation (wx_object) {
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    wx_object = null

    //const scope_userLocation = JSON.parse(window.localStorage.getItem('scope'))['scope.userLocation']
    PROMISE((SUCCESS, FAIL) => {
      //if (scope_userLocation) {
        navigator.geolocation.getCurrentPosition((web_position, error) => {
          if (error) {
            FAIL(error)
          }
          const web_coords = web_position.coords
          const wx_res = {
            latitude: web_coords.latitude,
            longitude: web_coords.longitude,
            altitude: web_coords.altitude,
            accuracy: web_coords.accuracy,
            heading: web_coords.heading,
            speed: web_coords.speed
          }
          SUCCESS(wx_res)
        });
      //} else {
        //const err = { errMsg: "getLocation:fail auth deny" }
        //FAIL(err)
      //}
    }, wx_success, wx_fail, wx_complete)
  }

  scanCode(wx_object) {
    const wx_onlyFromCamera = wx_object.onlyFromCamera | false
    const wx_scanType = wx_object.scanType | ['barCode', 'qrCode']
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    wx_object = null

    console.log(wx_onlyFromCamera, wx_scanType)

    window.open(`/onekit/pages/scanCode.html`, 'scanCode');

    PROMISE(SUCCESS => {
      const res = {
        errMsg: 'scanCode is not support now'
      }

      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  openLocation(wx_object) {
    const wx_latitude = wx_object.latitude
    const wx_longitude = wx_object.longitude
    const wx_scale = wx_object.scale
    const wx_name = wx_object.name
    const wx_address = wx_object.address
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    wx_object = null

    console.log(wx_latitude, wx_longitude, wx_scale, wx_name, wx_address)

    OneKit.current().$router.push({ path: '/onekit/openLocation', query: { latitude: wx_latitude, longitude: wx_longitude, name: wx_name, address: wx_address } })
    PROMISE((SUCCESS) => {
      const res = {
        errMsg: "openLocation:ok"
      }
      SUCCESS(res)
    }, wx_success, wx_fail, wx_complete)
  }

  authorize(wx_object) {
    const wx_scope = wx_object.scope
    const wx_success = wx_object.success
    const wx_fail = wx_object.fail
    const wx_complete = wx_object.complete
    wx_object = null

    const scope = JSON.parse(window.localStorage.getItem("scope"));
    const keys = Object.keys(scope)


    PROMISE((SUCCESS, FAIL) => {
      if (!keys.includes(wx_scope)) {
        let title
        let content
        switch (wx_scope) {
          case 'scope.camera':
            title = '使用你的摄像头'
            content = '将会上传你摄录的照片及视频'
            break;
          case 'scope.record':
            title = '使用你的麦克风'
            content = ''
            break;
          case 'scope.writePhotosAlbum':
            title = '保存图片或视频到你的相册'
            content = ''
            break;
          default:
            break;
        }

        if (wx_scope == 'scope.userLocation') {
          navigator.geolocation.getCurrentPosition(() => {
            scope['scope.userLocation'] = true
            localStorage.setItem('scope', JSON.stringify(scope))
            const res = {
              errMsg: "authorize:ok"
            }
            SUCCESS(res)
          }, () => {
            scope['scope.userLocation'] = false
            localStorage.setItem('scope', JSON.stringify(scope))
            const err = {
              errMsg: "authorize:fail auth deny"
            }
            FAIL(err)
          },
          )
        } else if (wx_scope == 'scope.userLocationBackground') {
          navigator.geolocation.getCurrentPosition(() => {
            scope['scope.userLocationBackground'] = true
            scope['scope.userLocation'] = true
            localStorage.setItem('scope', JSON.stringify(scope))
            const res = {
              errMsg: "authorize:ok"
            }
            SUCCESS(res)
          }, () => {
            scope['scope.userLocationBackground'] = false
            localStorage.setItem('scope', JSON.stringify(scope))
            const err = {
              errMsg: "authorize:fail auth deny"
            }
            FAIL(err)
          },
          )
        } else {
          const app = document.getElementById('app')
          const x = document.createElement('div')
          x.innerHTML = `
          <div
            style="
              background-color: #ededed;
              width: calc(100% - 40px);
              height: 160px;
              position: absolute;
              bottom: 0;
              padding: 20px;
              border-top-left-radius: 10px;
              border-top-right-radius: 10px;
              display: flex;
              flex-direction: column;
              justify-content: space-evenly;
            "
          >
            <div style="font-size: 14px">OnekitWX 申请</div>
            <div>
              <p style="font-size: 16px">${title}</p>
              <p style="font-size: 14px; color: #767676">${content}</p>
            </div>
            <div
              style="
                display: flex;
                flex-direction: row;
                justify-content: space-evenly;
              "
            >
              <button
                id="scopeRefuse"
                style="
                  width: 90px;
                  height: 30px;
                  color: #06ae56;
                  background-color: #fff;
                  border-radius: 5px;
                "
              >
                拒绝
              </button>
              <button
                id="scopeAllow"
                style="
                  width: 90px;
                  height: 30px;
                  color: #fff;
                  background-color: #06ae56;
                  border-radius: 5px;
                "
              >
                允许
              </button>
            </div>
          </div>`
          app.appendChild(x)

          document.getElementById('scopeAllow').addEventListener('click', () => {
            scope[wx_scope] = true
            localStorage.setItem('scope', JSON.stringify(scope))
            x.remove()
            const res = {
              errMsg: "authorize:ok"
            }
            SUCCESS(res)
          })

          document.getElementById('scopeRefuse').addEventListener('click', () => {
            scope[wx_scope] = false
            localStorage.setItem('scope', JSON.stringify(scope))
            x.remove()
            const err = {
              errMsg: "authorize:fail auth deny"
            }
            FAIL(err)
          })
        }
      } else {
        const err = {
          errMsg: 'authorize:fail 系统错误，错误码：-12006,auth deny'
        }
        FAIL(err)
      }
    }, wx_success, wx_fail, wx_complete)
  }
  
  getXrFrameSystem(){
    return new XrFrameSystem()
  }
}
export default new VueWX()

